using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Chat.Backend.Services.Contact
{
    /// <summary>
    /// 联系人管理服务 - 处理用户联系人的添加、删除和修改
    /// </summary>
    public class ContactService : IContactService
    {
        private readonly ILogger<ContactService> _logger;
        private readonly IContactRepository _contactRepository;
        private readonly IUserService _userService;
        private readonly IXmppService _xmppService;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ContactService(
            ILogger<ContactService> logger,
            IContactRepository contactRepository,
            IUserService userService,
            IXmppService xmppService)
        {
            _logger = logger;
            _contactRepository = contactRepository;
            _userService = userService;
            _xmppService = xmppService;
        }

        /// <summary>
        /// 获取用户的联系人列表
        /// </summary>
        public async Task<List<ContactInfo>> GetContactsAsync(string userId)
        {
            try
            {
                // 从数据库获取联系人ID列表
                var contactIds = await _contactRepository.GetContactIdsAsync(userId);
                
                // 获取每个联系人的详细信息
                var contacts = new List<ContactInfo>();
                foreach (var contactId in contactIds)
                {
                    var user = await _userService.GetUserByIdAsync(contactId);
                    if (user != null)
                    {
                        // 获取联系人备注信息
                        var remark = await _contactRepository.GetContactRemarkAsync(userId, contactId);
                        
                        contacts.Add(new ContactInfo
                        {
                            UserId = user.Id,
                            Nickname = user.Nickname,
                            Remark = remark?.Name,
                            AvatarUrl = user.AvatarUrl,
                            PhoneNumber = user.PhoneNumber,
                            IsOnline = await _userService.IsUserOnlineAsync(contactId),
                            Relation = ContactRelation.Friend,
                            CreateTime = remark?.CreateTime ?? DateTime.MinValue
                        });
                    }
                }
                
                // 按添加时间排序
                contacts.Sort((a, b) => b.CreateTime.CompareTo(a.CreateTime));
                
                return contacts;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取联系人列表失败: 用户ID {userId}");
                throw;
            }
        }

        /// <summary>
        /// 添加联系人
        /// </summary>
        public async Task<ContactResult> AddContactAsync(string userId, string contactId, string remark = null)
        {
            try
            {
                // 检查用户是否存在
                var user = await _userService.GetUserByIdAsync(userId);
                if (user == null)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "用户不存在"
                    };
                }
                
                // 检查联系人是否存在
                var contact = await _userService.GetUserByIdAsync(contactId);
                if (contact == null)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "联系人不存在"
                    };
                }
                
                // 检查是否已经是联系人
                var isContact = await _contactRepository.IsContactAsync(userId, contactId);
                if (isContact)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "该用户已经是您的联系人"
                    };
                }
                
                // 添加联系人
                var contactRemark = new ContactRemark
                {
                    UserId = userId,
                    ContactId = contactId,
                    Name = remark,
                    CreateTime = DateTime.UtcNow
                };
                
                await _contactRepository.AddContactAsync(contactRemark);
                
                // 默认双向好友关系
                var reverseRemark = new ContactRemark
                {
                    UserId = contactId,
                    ContactId = userId,
                    Name = null, // 对方未设置备注
                    CreateTime = DateTime.UtcNow
                };
                
                await _contactRepository.AddContactAsync(reverseRemark);
                
                // 发送系统消息
                var systemMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = "system",
                    ReceiverId = userId,
                    Content = $"您已添加 {contact.Nickname} 为联系人",
                    Type = MessageType.System,
                    IsGroupChat = false,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sent
                };
                
                await _chatRepository.SaveMessageAsync(systemMessage);
                
                // 给对方也发送系统消息
                var reverseSystemMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = "system",
                    ReceiverId = contactId,
                    Content = $"{user.Nickname} 已添加您为联系人",
                    Type = MessageType.System,
                    IsGroupChat = false,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sent
                };
                
                await _chatRepository.SaveMessageAsync(reverseSystemMessage);
                
                _logger.LogInformation($"用户 {userId} 添加联系人 {contactId}");
                
                return new ContactResult
                {
                    Success = true,
                    UserId = contactId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加联系人失败: 用户ID {userId}, 联系人ID {contactId}");
                return new ContactResult
                {
                    Success = false,
                    Error = "添加联系人失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除联系人
        /// </summary>
        public async Task<ContactResult> DeleteContactAsync(string userId, string contactId)
        {
            try
            {
                // 检查是否是联系人
                var isContact = await _contactRepository.IsContactAsync(userId, contactId);
                if (!isContact)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "该用户不是您的联系人"
                    };
                }
                
                // 删除联系人
                await _contactRepository.DeleteContactAsync(userId, contactId);
                
                // 可选：同时删除对方的联系人记录（双向删除）
                await _contactRepository.DeleteContactAsync(contactId, userId);
                
                // 发送系统消息
                var contact = await _userService.GetUserByIdAsync(contactId);
                var systemMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = "system",
                    ReceiverId = userId,
                    Content = $"您已删除联系人 {contact?.Nickname ?? contactId}",
                    Type = MessageType.System,
                    IsGroupChat = false,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sent
                };
                
                await _chatRepository.SaveMessageAsync(systemMessage);
                
                _logger.LogInformation($"用户 {userId} 删除联系人 {contactId}");
                
                return new ContactResult
                {
                    Success = true,
                    UserId = contactId
                };
            }
                        catch (Exception ex)
            {
                _logger.LogError(ex, $"删除联系人失败: 用户ID {userId}, 联系人ID {contactId}");
                return new ContactResult
                {
                    Success = false,
                    Error = "删除联系人失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 修改联系人备注
        /// </summary>
        public async Task<ContactResult> UpdateContactRemarkAsync(string userId, string contactId, string remark)
        {
            try
            {
                // 检查是否是联系人
                var isContact = await _contactRepository.IsContactAsync(userId, contactId);
                if (!isContact)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "该用户不是您的联系人"
                    };
                }
                
                // 修改备注
                await _contactRepository.UpdateContactRemarkAsync(userId, contactId, remark);
                
                _logger.LogInformation($"用户 {userId} 修改联系人 {contactId} 的备注为 {remark}");
                
                return new ContactResult
                {
                    Success = true,
                    UserId = contactId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改联系人备注失败: 用户ID {userId}, 联系人ID {contactId}");
                return new ContactResult
                {
                    Success = false,
                    Error = "修改联系人备注失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 搜索联系人
        /// </summary>
        public async Task<List<ContactInfo>> SearchContactsAsync(string userId, string keyword)
        {
            try
            {
                // 获取用户的所有联系人
                var contacts = await GetContactsAsync(userId);
                
                // 根据关键字过滤
                var results = contacts.FindAll(c => 
                    (c.Nickname != null && c.Nickname.Contains(keyword, StringComparison.OrdinalIgnoreCase)) || 
                    (c.Remark != null && c.Remark.Contains(keyword, StringComparison.OrdinalIgnoreCase)) ||
                    (c.PhoneNumber != null && c.PhoneNumber.Contains(keyword))
                );
                
                return results;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"搜索联系人失败: 用户ID {userId}, 关键字 {keyword}");
                throw;
            }
        }

        /// <summary>
        /// 接受好友请求
        /// </summary>
        public async Task<ContactResult> AcceptFriendRequestAsync(string userId, string requestId)
        {
            try
            {
                // 获取好友请求信息
                var request = await _contactRepository.GetFriendRequestAsync(requestId);
                if (request == null)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "好友请求不存在"
                    };
                }
                
                // 检查请求是否发给当前用户
                if (request.RecipientId != userId)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "无权处理该好友请求"
                    };
                }
                
                // 检查请求状态
                if (request.Status != FriendRequestStatus.Pending)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "该好友请求已被处理"
                    };
                }
                
                // 更新请求状态
                request.Status = FriendRequestStatus.Accepted;
                request.UpdateTime = DateTime.UtcNow;
                await _contactRepository.UpdateFriendRequestAsync(request);
                
                // 添加为好友（双向）
                var result = await AddContactAsync(userId, request.SenderId, request.Remark);
                
                // 发送系统消息通知请求发起方
                var recipient = await _userService.GetUserByIdAsync(userId);
                var systemMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = "system",
                    ReceiverId = request.SenderId,
                    Content = $"{recipient.Nickname} 已接受您的好友请求",
                    Type = MessageType.System,
                    IsGroupChat = false,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sent
                };
                
                await _chatRepository.SaveMessageAsync(systemMessage);
                
                // 发送XMPP消息通知对方
                var notifyMessage = new FriendRequestNotification
                {
                    Type = "friend_request_accepted",
                    RequestId = requestId,
                    UserId = userId,
                    Nickname = recipient.Nickname,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(notifyMessage);
                var xmppTo = $"{request.SenderId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                _logger.LogInformation($"用户 {userId} 接受好友请求 {requestId} 来自 {request.SenderId}");
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"接受好友请求失败: 用户ID {userId}, 请求ID {requestId}");
                return new ContactResult
                {
                    Success = false,
                    Error = "接受好友请求失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 拒绝好友请求
        /// </summary>
        public async Task<ContactResult> RejectFriendRequestAsync(string userId, string requestId)
        {
            try
            {
                // 获取好友请求信息
                var request = await _contactRepository.GetFriendRequestAsync(requestId);
                if (request == null)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "好友请求不存在"
                    };
                }
                
                // 检查请求是否发给当前用户
                if (request.RecipientId != userId)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "无权处理该好友请求"
                    };
                }
                
                // 检查请求状态
                if (request.Status != FriendRequestStatus.Pending)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "该好友请求已被处理"
                    };
                }
                
                // 更新请求状态
                request.Status = FriendRequestStatus.Rejected;
                request.UpdateTime = DateTime.UtcNow;
                await _contactRepository.UpdateFriendRequestAsync(request);
                
                // 发送系统消息通知请求发起方（可选）
                var recipient = await _userService.GetUserByIdAsync(userId);
                var systemMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = "system",
                    ReceiverId = request.SenderId,
                    Content = $"{recipient.Nickname} 已拒绝您的好友请求",
                    Type = MessageType.System,
                    IsGroupChat = false,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sent
                };
                
                await _chatRepository.SaveMessageAsync(systemMessage);
                
                // 发送XMPP消息通知对方
                var notifyMessage = new FriendRequestNotification
                {
                    Type = "friend_request_rejected",
                    RequestId = requestId,
                    UserId = userId,
                    Nickname = recipient.Nickname,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(notifyMessage);
                var xmppTo = $"{request.SenderId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                _logger.LogInformation($"用户 {userId} 拒绝好友请求 {requestId} 来自 {request.SenderId}");
                
                return new ContactResult
                {
                    Success = true,
                    UserId = request.SenderId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"拒绝好友请求失败: 用户ID {userId}, 请求ID {requestId}");
                return new ContactResult
                {
                    Success = false,
                    Error = "拒绝好友请求失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 发送好友请求
        /// </summary>
        public async Task<ContactResult> SendFriendRequestAsync(string senderId, string recipientId, string message = null, string remark = null)
        {
            try
            {
                // 检查发送者和接收者是否存在
                var sender = await _userService.GetUserByIdAsync(senderId);
                var recipient = await _userService.GetUserByIdAsync(recipientId);
                
                if (sender == null || recipient == null)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "用户不存在"
                    };
                }
                
                // 检查是否已经是好友
                var isContact = await _contactRepository.IsContactAsync(senderId, recipientId);
                if (isContact)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "该用户已经是您的联系人"
                    };
                }
                
                // 检查是否已经发送过请求且未处理
                var existingRequest = await _contactRepository.GetPendingFriendRequestAsync(senderId, recipientId);
                if (existingRequest != null)
                {
                    return new ContactResult
                    {
                        Success = false,
                        Error = "您已经向该用户发送过好友请求，请等待对方处理"
                    };
                }
                
                // 创建好友请求
                var friendRequest = new FriendRequest
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = senderId,
                    SenderNickname = sender.Nickname,
                    RecipientId = recipientId,
                    Message = message,
                    Remark = remark,
                    Status = FriendRequestStatus.Pending,
                    CreateTime = DateTime.UtcNow,
                    UpdateTime = DateTime.UtcNow
                };
                
                await _contactRepository.SaveFriendRequestAsync(friendRequest);
                
                // 发送系统消息通知接收方
                var systemMessage = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = "system",
                    ReceiverId = recipientId,
                    Content = $"{sender.Nickname} 请求添加您为好友" + (!string.IsNullOrEmpty(message) ? $": {message}" : ""),
                    Type = MessageType.System,
                    IsGroupChat = false,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sent
                };
                
                await _chatRepository.SaveMessageAsync(systemMessage);
                
                // 发送XMPP消息通知对方
                var notifyMessage = new FriendRequestNotification
                {
                    Type = "friend_request",
                    RequestId = friendRequest.Id,
                    UserId = senderId,
                    Nickname = sender.Nickname,
                    Message = message,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(notifyMessage);
                var xmppTo = $"{recipientId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                _logger.LogInformation($"用户 {senderId} 向 {recipientId} 发送好友请求");
                
                return new ContactResult
                {
                    Success = true,
                    UserId = recipientId,
                    RequestId = friendRequest.Id
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送好友请求失败: 发送者 {senderId}, 接收者 {recipientId}");
                return new ContactResult
                {
                    Success = false,
                    Error = "发送好友请求失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取好友请求列表
        /// </summary>
        public async Task<List<FriendRequest>> GetFriendRequestsAsync(string userId, FriendRequestDirection direction = FriendRequestDirection.Received)
        {
            try
            {
                if (direction == FriendRequestDirection.Received)
                {
                    return await _contactRepository.GetReceivedFriendRequestsAsync(userId);
                }
                else
                {
                    return await _contactRepository.GetSentFriendRequestsAsync(userId);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取好友请求列表失败: 用户ID {userId}, 方向 {direction}");
                throw;
            }
        }

        /// <summary>
        /// 创建联系人分组
        /// </summary>
        public async Task<ContactGroupResult> CreateContactGroupAsync(string userId, string groupName)
        {
            try
            {
                // 检查分组名称是否为空
                if (string.IsNullOrWhiteSpace(groupName))
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "分组名称不能为空"
                    };
                }
                
                // 检查是否已存在同名分组
                var existingGroup = await _contactRepository.GetContactGroupByNameAsync(userId, groupName);
                if (existingGroup != null)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "已存在同名分组"
                    };
                }
                
                // 创建分组
                var group = new ContactGroup
                {
                    Id = Guid.NewGuid().ToString(),
                    UserId = userId,
                    Name = groupName,
                    CreateTime = DateTime.UtcNow,
                    UpdateTime = DateTime.UtcNow
                };
                
                await _contactRepository.SaveContactGroupAsync(group);
                
                _logger.LogInformation($"用户 {userId} 创建联系人分组 {groupName}");
                
                return new ContactGroupResult
                {
                    Success = true,
                    GroupId = group.Id,
                    GroupName = groupName
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建联系人分组失败: 用户ID {userId}, 分组名 {groupName}");
                return new ContactGroupResult
                {
                    Success = false,
                    Error = "创建联系人分组失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除联系人分组
        /// </summary>
        public async Task<ContactGroupResult> DeleteContactGroupAsync(string userId, string groupId)
        {
            try
            {
                // 获取分组信息
                var group = await _contactRepository.GetContactGroupByIdAsync(groupId);
                if (group == null)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "分组不存在"
                    };
                }
                
                // 检查分组是否属于当前用户
                if (group.UserId != userId)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "无权删除该分组"
                    };
                }
                
                // 获取分组中的联系人
                var contactIds = await _contactRepository.GetContactIdsByGroupAsync(groupId);
                
                // 将这些联系人移动到默认分组
                foreach (var contactId in contactIds)
                {
                    await _contactRepository.RemoveContactFromGroupAsync(userId, contactId, groupId);
                }
                
                // 删除分组
                await _contactRepository.DeleteContactGroupAsync(groupId);
                
                _logger.LogInformation($"用户 {userId} 删除联系人分组 {group.Name}");
                
                return new ContactGroupResult
                {
                    Success = true,
                    GroupId = groupId,
                    GroupName = group.Name
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除联系人分组失败: 用户ID {userId}, 分组ID {groupId}");
                return new ContactGroupResult
                {
                    Success = false,
                    Error = "删除联系人分组失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 修改联系人分组名称
        /// </summary>
        public async Task<ContactGroupResult> UpdateContactGroupNameAsync(string userId, string groupId, string newName)
        {
            try
            {
                // 获取分组信息
                var group = await _contactRepository.GetContactGroupByIdAsync(groupId);
                if (group == null)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "分组不存在"
                    };
                }
                
                // 检查分组是否属于当前用户
                if (group.UserId != userId)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "无权修改该分组"
                    };
                }
                
                // 检查是否已存在同名分组
                var existingGroup = await _contactRepository.GetContactGroupByNameAsync(userId, newName);
                if (existingGroup != null && existingGroup.Id != groupId)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "已存在同名分组"
                    };
                }
                
                // 修改分组名称
                group.Name = newName;
                group.UpdateTime = DateTime.UtcNow;
                await _contactRepository.UpdateContactGroupAsync(group);
                
                _logger.LogInformation($"用户 {userId} 修改联系人分组名称 {group.Name} -> {newName}");
                
                return new ContactGroupResult
                {
                    Success = true,
                    GroupId = groupId,
                    GroupName = newName
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改联系人分组名称失败: 用户ID {userId}, 分组ID {groupId}");
                return new ContactGroupResult
                {
                    Success = false,
                    Error = "修改联系人分组名称失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 将联系人添加到分组
        /// </summary>
        public async Task<ContactGroupResult> AddContactToGroupAsync(string userId, string contactId, string groupId)
        {
            try
            {
                // 检查是否是联系人
                var isContact = await _contactRepository.IsContactAsync(userId, contactId);
                if (!isContact)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "该用户不是您的联系人"
                    };
                }
                
                // 获取分组信息
                var group = await _contactRepository.GetContactGroupByIdAsync(groupId);
                if (group == null)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "分组不存在"
                    };
                }
                
                // 检查分组是否属于当前用户
                if (group.UserId != userId)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "无权操作该分组"
                    };
                }
                
                // 将联系人添加到分组
                await _contactRepository.AddContactToGroupAsync(userId, contactId, groupId);
                
                _logger.LogInformation($"用户 {userId} 将联系人 {contactId} 添加到分组 {group.Name}");
                
                return new ContactGroupResult
                {
                    Success = true,
                    GroupId = groupId,
                    GroupName = group.Name,
                    ContactId = contactId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"将联系人添加到分组失败: 用户ID {userId}, 联系人ID {contactId}, 分组ID {groupId}");
                return new ContactGroupResult
                {
                    Success = false,
                    Error = "将联系人添加到分组失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 从分组中移除联系人
        /// </summary>
        public async Task<ContactGroupResult> RemoveContactFromGroupAsync(string userId, string contactId, string groupId)
        {
            try
            {
                // 获取分组信息
                var group = await _contactRepository.GetContactGroupByIdAsync(groupId);
                if (group == null)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "分组不存在"
                    };
                }
                
                // 检查分组是否属于当前用户
                if (group.UserId != userId)
                {
                    return new ContactGroupResult
                    {
                        Success = false,
                        Error = "无权操作该分组"
                    };
                }
                
                // 从分组中移除联系人
                await _contactRepository.RemoveContactFromGroupAsync(userId, contactId, groupId);
                
                _logger.LogInformation($"用户 {userId} 将联系人 {contactId} 从分组 {group.Name} 中移除");
                
                return new ContactGroupResult
                {
                    Success = true,
                    GroupId = groupId,
                    GroupName = group.Name,
                    ContactId = contactId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从分组中移除联系人失败: 用户ID {userId}, 联系人ID {contactId}, 分组ID {groupId}");
                return new ContactGroupResult
                {
                    Success = false,
                    Error = "从分组中移除联系人失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取用户的联系人分组列表
        /// </summary>
        public async Task<List<ContactGroupInfo>> GetContactGroupsAsync(string userId)
        {
            try
            {
                // 获取分组列表
                var groups = await _contactRepository.GetContactGroupsByUserIdAsync(userId);
                
                // 获取每个分组中的联系人数量
                var result = new List<ContactGroupInfo>();
                foreach (var group in groups)
                {
                    var contactIds = await _contactRepository.GetContactIdsByGroupAsync(group.Id);
                    
                    result.Add(new ContactGroupInfo
                    {
                        Id = group.Id,
                        Name = group.Name,
                        ContactCount = contactIds.Count,
                        CreateTime = group.CreateTime,
                        UpdateTime = group.UpdateTime
                    });
                }
                
                // 按创建时间排序
                result.Sort((a, b) => a.CreateTime.CompareTo(b.CreateTime));
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取联系人分组列表失败: 用户ID {userId}");
                throw;
            }
        }

        /// <summary>
        /// 获取分组中的联系人列表
        /// </summary>
        public async Task<List<ContactInfo>> GetContactsByGroupAsync(string userId, string groupId)
        {
            try
            {
                // 检查分组是否存在
                var group = await _contactRepository.GetContactGroupByIdAsync(groupId);
                if (group == null)
                {
                    throw new ArgumentException($"分组不存在: {groupId}");
                }
                
                // 检查分组是否属于当前用户
                if (group.UserId != userId)
                {
                    throw new UnauthorizedAccessException("无权访问该分组");
                }
                
                // 获取分组中的联系人ID列表
                var contactIds = await _contactRepository.GetContactIdsByGroupAsync(groupId);
                
                // 获取每个联系人的详细信息
                var contacts = new List<ContactInfo>();
                foreach (var contactId in contactIds)
                {
                    var user = await _userService.GetUserByIdAsync(contactId);
                    if (user != null)
                    {
                        // 获取联系人备注信息
                        var remark = await _contactRepository.GetContactRemarkAsync(userId, contactId);
                        
                        contacts.Add(new ContactInfo
                        {
                            UserId = user.Id,
                            Nickname = user.Nickname,
                            Remark = remark?.Name,
                            AvatarUrl = user.AvatarUrl,
                            PhoneNumber = user.PhoneNumber,
                            IsOnline = await _userService.IsUserOnlineAsync(contactId),
                            Relation = ContactRelation.Friend,
                            CreateTime = remark?.CreateTime ?? DateTime.MinValue
                        });
                    }
                }
                
                // 按添加时间排序
                contacts.Sort((a, b) => b.CreateTime.CompareTo(a.CreateTime));
                
                return contacts;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取分组联系人列表失败: 用户ID {userId}, 分组ID {groupId}");
                throw;
            }
        }
    }

    /// <summary>
    /// 联系人管理服务接口
    /// </summary>
    public interface IContactService
    {
        Task<List<ContactInfo>> GetContactsAsync(string userId);
        Task<ContactResult> AddContactAsync(string userId, string contactId, string remark = null);
        Task<ContactResult> DeleteContactAsync(string userId, string contactId);
        Task<ContactResult> UpdateContactRemarkAsync(string userId, string contactId, string remark);
        Task<List<ContactInfo>> SearchContactsAsync(string userId, string keyword);
        Task<ContactResult> SendFriendRequestAsync(string senderId, string recipientId, string message = null, string remark = null);
        Task<ContactResult> AcceptFriendRequestAsync(string userId, string requestId);
        Task<ContactResult> RejectFriendRequestAsync(string userId, string requestId);
        Task<List<FriendRequest>> GetFriendRequestsAsync(string userId, FriendRequestDirection direction = FriendRequestDirection.Received);
        Task<ContactGroupResult> CreateContactGroupAsync(string userId, string groupName);
        Task<ContactGroupResult> DeleteContactGroupAsync(string userId, string groupId);
        Task<ContactGroupResult> UpdateContactGroupNameAsync(string userId, string groupId, string newName);
        Task<ContactGroupResult> AddContactToGroupAsync(string userId, string contactId, string groupId);
        Task<ContactGroupResult> RemoveContactFromGroupAsync(string userId, string contactId, string groupId);
        Task<List<ContactGroupInfo>> GetContactGroupsAsync(string userId);
        Task<List<ContactInfo>> GetContactsByGroupAsync(string userId, string groupId);
    }
}